package org.kent.w.base.common.validate.validator;

import lombok.extern.slf4j.Slf4j;
import org.kent.w.base.common.enums.IntEnum;
import org.kent.w.base.common.enums.StringEnum;
import org.kent.w.base.common.validate.constraints.IntEnumValue;
import org.kent.w.base.common.validate.constraints.StringEnumValue;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Enum Value ConstraintValidator
 *
 * @author wujigang
 * @date 2019/9/17
 */
@Slf4j
public class StringEnumValueConstraintValidator implements ConstraintValidator<StringEnumValue, String> {

    private Class<? extends StringEnum> enumClass;

    @Override
    public void initialize(StringEnumValue stringEnumValue) {
        this.enumClass = stringEnumValue.enumClass();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        if (value == null || value.length() <= 0 || enumClass == null) {
            return false;
        }

        StringEnum[] enumConstants = enumClass.getEnumConstants();

        for (StringEnum e : enumConstants) {
            if (e.getCode().equals(value)) {
                return true;
            }
        }

        return false;
    }
}
